﻿package component.tree.web.view;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import component.tree.entity.Tree;
import component.tree.util.ConfigUtil;
import component.tree.util.StringUtil;
import component.tree.util.TreeUtil;


public class TreeView extends BaseTreeView{
	public TreeView(){
		super();
	}

	public TreeView(String context,List treeList){
		super(context, treeList);
	}
	
	public TreeView(String treeObj,String context,List treeList){
		super(treeObj, context, treeList);
	}
	
	private String getImageSrc(String imagePath){
		return imagePath;
	}
	
	public String toString(){
		//如果搜索条件不为空就展开所有
		if(!StringUtil.isNull(this.searchName)){
			this.firstShowLevel = 4;
		}
		
		StringBuffer sb = new StringBuffer(1000);
		this.setInitJs(sb);
		
		int level = 1;
		sb.append("<div class='"+ConfigUtil.getTreeCssName()+"'>" + getLineBreak());
		
		sb.append(getSpacesByLevel(level)+"<div class='" + ConfigUtil.getTreeNodeCssName() + "'>" + getLineBreak());
		if(this.isUseBaseIcon && !StringUtil.isNull(this.title))
			sb.append(getSpacesByLevel(level+1)+"<img id='id0' src='" + getImageSrc(ConfigUtil.getRootImageName()) + "' alt='' />");
		if(!this.isUseBaseIcon && this.isSelectMore && !StringUtil.isNull(this.title)){
			sb.append("<input style='height:15px;width:15' type='checkbox' value='0' onclick='"+treeObj+".onNodeSelect(this)' ");
			sb.append("id='0' name='" + CHECKBOX_NAME_PREX + "-1' path='0' />");
		}
		if(!StringUtil.isNull(this.title)){
			sb.append(this.title);
		}
		sb.append(getLineBreak());
		sb.append(getSpacesByLevel(level)+"</div>" + getLineBreak());
	
		
		sb.append(getSpacesByLevel(level)+"<div id='"+DIV_ID_PREX+rootId+"' class='"+ConfigUtil.getParentNodeCssName()+"' style='display:block;'>"+ getLineBreak());
		
		//树型数据
		if(treeList!=null && !treeList.isEmpty()){
			Tree rootTree = new Tree();
			rootTree.setId(Tree.ROOT_ID);rootTree.setLevel(0);rootTree.setLast(true);rootTree.setPath("0");
			rootTree.setType(1);rootTree.setChildList(treeList);
			sb.append(this.getTreeNodeHtml(rootTree));
		}
		
		sb.append(getSpacesByLevel(level)+"</div>"+ getLineBreak());
		
		sb.append("</div>"+ getLineBreak());
		
		return sb.toString();
	}
	
	//伸缩图片的点击事件
	private String getChangeStateEvent(Tree vo){
		return "javascript:"+treeObj+".onChangeState(\""+DIV_ID_PREX+vo.getId()+"\");";
	}
	//节点的点击事件
	private String getClickNodeEvent(Tree vo){
		String str = "javascript:";
		if(!(this.isTarget || !StringUtil.isNull(url))){
			str += "event.returnValue=false;";
		}
		str += treeObj+".onClickNode(\""+DIV_ID_PREX+vo.getId()+"\");";
		return str;
	}
	
	private String getDblClickNodeEvent(Tree vo){
		String str = "javascript:";
		if(!this.isSelectMore){
			str += treeObj+".onDblClickNode(\""+DIV_ID_PREX+vo.getId()+"\");";
		}
		return str;
	}
	
	/**
	 * 子节点的层次根据父节点的层次获取，子节点的type根据childList是否为空获取
	 * 说明：同一层的节点的布局:是否使用虚线，是否使用图片
	 * 		1.目录：
	 * 			1)前面的目录：plus.gif(plusbottom.gif) + folder.gif
	 * 			2)最后的目录：plusbottom.gif(plusbottom.gif) + folder.gif
	 * 		2.叶子：
	 * 			1)前面的叶子：join.gif(empty.gif) + page.gif
	 * 			2)最后的叶子：joinbottom.gif(empty.gif) + page.gif
	 */
	public String getTreeNodeHtml(Tree parentVO){
		StringBuffer sb = new StringBuffer(1000);
		
		List treeList = parentVO.getChildList();
		if(treeList==null || treeList.isEmpty()) return "";
		
		int size = treeList.size();
		if(!StringUtil.isNull(this.orderField)){//对该层数据进行排序
			Map map = new HashMap();//<排序值,list>
			for(int i=0;i<size;i++){
				Tree vo = (Tree)treeList.get(i);
				String orderFieldValue = vo.getValue(this.orderField);
				if(StringUtil.isNull(orderFieldValue)) orderFieldValue = "";
				List list = (List)map.get(orderFieldValue);
				if(list==null) list = new ArrayList();
				list.add(vo);
				map.put(orderFieldValue, list);
			}	
			Set set = map.keySet();
			String[] orders = new String[set.size()];
			Iterator iter = set.iterator();
			int i=0;
			while(iter.hasNext()){
				orders[i] = (String)iter.next();
				i++;
			}
			Arrays.sort(orders);
			List treeList2 = new ArrayList();
			for(int j=0;j<orders.length;j++){
				String key = orders[j];
				List temp = (List)map.get(key);
				treeList2.addAll(temp);
			}
			treeList = treeList2;
		}
	
		for(int i=0;i<size;i++){
			Tree childVO = (Tree)treeList.get(i);
			childVO = this.getTree(parentVO, childVO);

			//设置isLast属性
			String parentLastStr = parentVO.getIsLastStr();
			if(i==size-1){
				childVO.setLast(true);
				childVO.setIsLastStr(parentLastStr + ",true");
			}else{
				childVO.setLast(false);
				childVO.setIsLastStr(parentLastStr + ",false");
			}
			
			sb.append(getSpacesByLevel(childVO.getLevel())+"<div value='"+TreeUtil.getDivValue(childVO)+"' class='"+ConfigUtil.getTreeNodeCssName()+"'>"+ getLineBreak());
			
			//设置连接父子节点的线:从第二层开始
			this.setJoinImg(parentVO,childVO, sb,size,i);
		
			//设置展开或缩回的图片
			this.setImg1(parentVO, childVO, sb, size,i);
			
			//设置目录或叶子的图片
			this.setImg2(childVO, sb);
			
			//设置CheckBox
			this.setCheckBox(parentVO, childVO, sb);
			
			//设置节点名称
			this.setNodeName(childVO, sb);
			
			sb.append(getSpacesByLevel(childVO.getLevel())+"</div>"+ getLineBreak());
			
			//如果有子节点就继续下面
			if(childVO.getType()==Tree.TYPE_1){
				sb.append(getLineBreak());
				
				String disPlay = "none";String isOpen = "false";
				if(this.isLoadAll && childVO.getLevel()<this.firstShowLevel){
					disPlay = "block";isOpen = "true";
				}
				sb.append(getSpacesByLevel(childVO.getLevel())+"<div isOpen='"+isOpen+"' id='"+DIV_ID_PREX+childVO.getId()+"' class='"+ConfigUtil.getParentNodeCssName()+"' style='display:"+disPlay+";'>"+ getLineBreak());
				
				//保存div的id,用于显示或隐藏所有子节点
				sb.append(getSpacesByLevel(childVO.getLevel()));
				sb.append("<SCRIPT LANGUAGE='JavaScript'>");
				sb.append(this.treeObj+".childDivIdArr.push('"+DIV_ID_PREX+childVO.getId()+"')");
				sb.append("</SCRIPT>"+ getLineBreak());
				
				if(this.isLoadAll)
					sb.append(this.getTreeNodeHtml(childVO));//递归显示子节点
				
				sb.append(getSpacesByLevel(childVO.getLevel())+"</div>"+ getLineBreak());
				sb.append(getLineBreak());
			}
		}
		return sb.toString();
	}
	
	//是否使用空白图片
	private boolean isUseEmptyImg(String[] isLastStrArr,int j){
		if(!this.isUseLines) return true;
		if(isLastStrArr[j-1].equals("true")){
			return true;
		}
		return false;
	}
	
	private void setJoinImg(Tree parentVO,Tree childVO,StringBuffer sb,int size,int i){
		String joinImg = "";
		String isLastStr = childVO.getIsLastStr();
		String[] isLastStrArr = isLastStr.split(",");
		int level = childVO.getLevel();
		for(int j=2;j<=level;j++){
			if(this.isUseEmptyImg(isLastStrArr,j))
				joinImg = ConfigUtil.getEmptyImageName();
			else
				joinImg = ConfigUtil.getLineImageName();
			sb.append(getSpacesByLevel(childVO.getLevel()+1)+"<img src='"+getImageSrc(joinImg)+"' alt='' />"+ getLineBreak());
		}
	}
	
	private void setImg1(Tree parentVO,Tree childVO,StringBuffer sb,int size,int i){
		String img1 = "";//展开或缩回的图片
		if(childVO.getType()==Tree.TYPE_1){//目录
			if(this.isLoadAll && childVO.getLevel()<firstShowLevel){//前面几层显示
				if(this.isUseLines){
					img1 = ConfigUtil.getMinusImageName();//前面的节点
					if(i==treeList.size()-1){//最后一个节点
						img1 = ConfigUtil.getMinusbottomImageName();
					}
				}else{
					img1 = ConfigUtil.getNolinesMinusImageName();
				}
			}else{
				if(this.isUseLines){
					img1 = ConfigUtil.getPlusImageName();//前面的节点
					if(i==size-1){//最后一个节点
						img1 = ConfigUtil.getPlusbottomImageName();
					}
				}else{
					img1 = ConfigUtil.getNolinesPlusImageName();
				}
			}
		}else{//叶子
			if(this.isUseLines){
				img1 = ConfigUtil.getJoinImageName();//中间的节点:连接上下节点
				if(i==size-1){//最后一个节点
					img1 = ConfigUtil.getJoinbottomImageName();
				}
			}else{
				img1 = ConfigUtil.getEmptyImageName();
			}
		}	
		sb.append(getSpacesByLevel(childVO.getLevel()+1)+"<img onclick='"+this.getChangeStateEvent(childVO)+"' id='"+IMAGE1_ID_PREX+childVO.getId()+"' src='"+getImageSrc(img1)+"' alt='' />"+ getLineBreak());
		
	}
	
	private void setImg2(Tree childVO,StringBuffer sb){
		if(this.isUseIcons){
			String img2 = "";//目录或叶子的图片
			if(childVO.getType()==Tree.TYPE_1){//目录
				if(this.isLoadAll && childVO.getLevel()<firstShowLevel){//前面几层显示
					img2 = ConfigUtil.getFolderopenImageName();
				}else{
					img2 = ConfigUtil.getFolderImageName();
				}
			}else{//叶子
				img2 = ConfigUtil.getPageImageName();
			}
			String jsEvent = "";
			//双击可以伸缩
			if(childVO.getType()==Tree.TYPE_1) jsEvent = "ondblclick='"+this.getChangeStateEvent(childVO)+"'";
			sb.append(getSpacesByLevel(childVO.getLevel()+1)+"<img " + jsEvent + " id='"+IMAGE2_ID_PREX + childVO.getId() + "' src='"+getImageSrc(img2)+"' alt='' />"+ getLineBreak());
		}
	}
	
	private void setCheckBox(Tree parentVO,Tree childVO,StringBuffer sb){
		if(this.isSelectMore){
			if(childVO.getType()==Tree.TYPE_0 || (childVO.getType()==Tree.TYPE_1 && this.isSelectFolder)){
				sb.append(getSpacesByLevel(childVO.getLevel()+1)+"<input style='height:15px;width:15' type='checkbox' value='"+childVO.getId()+"' onclick='"+treeObj+".onNodeSelect(this)' ");
				sb.append("id='"+childVO.getId()+"' name='" + CHECKBOX_NAME_PREX + parentVO.getId() + "' path='"+childVO.getPath()+"' />");
			}
		}
	}
	private void setNodeName(Tree childVO,StringBuffer sb){
		sb.append(getSpacesByLevel(childVO.getLevel()+1)+"<a href='");
		if(this.isTarget || !StringUtil.isNull(url)){
			sb.append(this.url);
			if(this.url.indexOf("?")==-1){
				sb.append("?");
			}else{
				sb.append("&");
			}
			sb.append("parentId="+childVO.getId());
		}else{
			sb.append("#");
		}
		sb.append("' target='"+this.target+"' onclick='"+this.getClickNodeEvent(childVO)+"' ondblclick='"+this.getDblClickNodeEvent(childVO)+"'  class='"+ConfigUtil.getTreeNodeCssName()+"'>");
		sb.append(childVO.getName()+"</a>"+ getLineBreak());
	}
	
	private Tree getTree(Tree parentVO,Tree childVO){
		//设置完整的名称
		String names = parentVO.getName();
		if(!StringUtil.isNull(names)){
			childVO.setAllName(names+"-" + childVO.getName());
		}else{
			childVO.setAllName(childVO.getName());
		}
		
		String path = parentVO.getPath() + "," + childVO.getId();
		childVO.setPath(path);
		
		int level = parentVO.getLevel() + 1;
		childVO.setLevel(level);//需要重新设置level
		
		int type = Tree.TYPE_1;
		if(this.isLoadAll){
			List child2List = childVO.getChildList();
			if(child2List==null || child2List.isEmpty()){
				type = Tree.TYPE_0;
			}
		}else{
			type = childVO.getType();
		}
		childVO.setType(type);//需要重新设置type
		return childVO;
	}
	
	private String getSpacesByLevel(int level){
		if(!this.isCreateCode) return "";
		String spaces = "  ";
		for(int i=0;i<level;i++){
			spaces += SPACES;
		}
		return spaces;
	}
	private String getLineBreak(){
		if(!this.isCreateCode) return "";
		return LINE_BREAK;
	}
}
